<?php

namespace App\Http\Controllers\Admin;

use App\Exports\QhCdkeyExport;
use App\Http\Requests\Admin\Qh_CdkeyBetchCreateRequest;
use App\Models\Qh_Cdkey;
use App\Models\Qh_CdkeyGroup;
use Carbon\Carbon;
use DB;
use Illuminate\Http\JsonResponse;
use Maatwebsite\Excel\Facades\Excel;
use PHPUnit\Util\Exception;
use Throwable;

class Qh_CdkeyController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = Qh_Cdkey::filter(\request()->all())
            ->with(['user' => function($q) {
                $q->select(['id', 'username', 'nickname', 'avatar']);
            }])
            ->with(['course' => function($q) {
                $q->select(['id', 'name']);
            }])
            ->orderByDesc('id')
            ->paginate(\request('perPage', 10));
        return $this->restful($list);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     */
    public function destroy(int $id)
    {
        $cdkey = Qh_Cdkey::findOrFail($id);
        $cdkey->delete();

        return $this->restful();
    }

    /**
     * 冻结/解冻
     * @param $id
     * @return JsonResponse|object
     * @throws Throwable
     */
    public function freeze($id) {
        $cdkey = Qh_Cdkey::findOrFail($id);

        try {
            if ($cdkey->status == 2) {
                DB::transaction(function () use ($cdkey){
                    $cdkey->status = 4;
                    $cdkey->save();

                    // 删除用户拥有的学科
                    DB::table('qh_user_has_course')->where('userId', $cdkey->userId)->where('courseId', $cdkey->activeCourseId)->where('type', 2)->delete();
                });

            }
            elseif ($cdkey->status == 4) {
                DB::transaction(function () use ($cdkey){
                    $cdkey->status = 2;
                    $cdkey->save();

                    // 恢复用户拥有的学科
                    DB::table('qh_user_has_course')->updateOrInsert([
                        'sourceId' => $cdkey->id,
                        'userId' => $cdkey->userId,
                        'courseId' => $cdkey->activeCourseId,
                        'type' => 2,
                        'created_at' => Carbon::now()
                    ]);
                });
            }
        }catch (\Exception $e) {
            throw new Exception('操作失败');
        }

        return $this->restful();
    }

    /**
     * 扩展生成激活码
     * @throws Throwable
     */
    public function extend()
    {
        $params = \request()->validate([
            'groupId' => 'bail|nullable|integer|exists:qh_cdkey_groups,id',
            'expires' => 'bail|nullable|integer',
            'count' => 'bail|required|integer',
        ], \request()->all());

        $cdkeyGroup = Qh_CdkeyGroup::findOrFail($params['groupId']);

        try {
            DB::beginTransaction();
            // 生成激活码
            for ($i=0; $i<$params['count'];$i++) {
                Qh_Cdkey::create([
                    'groupId' => $params['groupId'],
                    'code' => generateCdkey(),
                    'expires' => !empty($params['expires']) ? Carbon::createFromTimestamp($params['expires'], 'Asia/Shanghai') : $cdkeyGroup->expires,
                    'courseId' => $cdkeyGroup->courseId
                ]);
            }

            $cdkeyGroup->count = $cdkeyGroup->count + $params['count'];
            $cdkeyGroup->save();
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            throw new \Exception('生成失败');
        }

        return $this->restful();
    }

    /**
     * 批量删除
     * @return JsonResponse|object
     */
    public function cdkeyBatchDelete() {
        $ids = \request('ids', []);
        if (count($ids) > 0) {
            $cdkeyList = Qh_Cdkey::whereIn('id', $ids)->get();
            foreach ($cdkeyList as $cdkey) {
                $cdkey->delete();
            }
        }

        return $this->restful();
    }

    /**
     * @throws \Exception
     */
    public function export()
    {
        $ids = request('ids', []);
        if (count($ids) < 1)  throw new \Exception('缺少参数');
        $filename = '激活码'.time().'.xlsx';

        try {
            $result = Excel::store(new QhCdkeyExport(['ids' => $ids]), $filename, 'public');
            if (!$result) throw new \Exception('导出失败');
        }catch (\Exception $e) {
            throw new \Exception('导出失败');
        }

        return $this->restful([
            'filename' => $filename,
            'url' => \Storage::disk('public')->url($filename)
        ]);
    }

    /**
     * 批量创建
     * @param Qh_CdkeyBetchCreateRequest $request
     * @return JsonResponse|object
     */
    public function cdkeyBatchCreate(Qh_CdkeyBetchCreateRequest $request) {
        $params = $request->validated();

        $cdkey = [];
        // 双表
        // $cdkeyGroup

        for ($i=0; $i<$params['count'];$i++) {
            $cdkey[] = [
                'code' => 'CDKEY'.rand(1000000, 9999999),
            ];
            // Qh_Cdkey::create([
            //     'code' => 'CDKEY'.rand(1000000, 9999999),
            //     'courseId' => $params['courseId']
            // ]);
        }

        // 入库
        $cdkeyGroup = Qh_CdkeyGroup::create($params);

        return $this->restful();
    }
}
